package com.yoyo.ad.api;

import android.content.Context;


import com.yoyo.ad.utils.converter.StringConverterFactory;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.yoyo.ad.api.YoYoConfig.AD_HOST;


/**
 * Author Dollkey
 * Date 2017/8/24 9:20.
 */

public class ApiManage {

    private static ApiManage apiManage;

    public Context mContext;
    public OkHttpClient.Builder client;

    private static final int NO_TIME_LIMIT = 0;
    private static final int TIME_FIVE_SECOND = 5;

    public void init(Context context) {
        mContext = context;
        client = new OkHttpClient.Builder();
    }

    public static ApiManage getInstance() {
        if (apiManage == null) {
            synchronized (ApiManage.class) {
                if (apiManage == null) {
                    apiManage = new ApiManage();
                }
            }
        }
        return apiManage;
    }

    public <T> T getApi(Class<T> cls) {
        return getApi(null, TIME_FIVE_SECOND, cls, true);
    }

    public <T> T getApi(Class<T> cls, boolean converterFactory) {
        return getApi(null, TIME_FIVE_SECOND, cls, converterFactory);
    }

    public <T> T getApi(String url, Class<T> cls) {
        return getApi(url, TIME_FIVE_SECOND, cls, true);
    }

    public <T> T getApi(int time, Class<T> cls) {
        return getApi(null, time, cls, true);
    }

    public <T> T getApi(String url, int time, Class<T> cls, boolean converterFactory) {
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(url == null ? AD_HOST : url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        if (converterFactory) {
            builder.addConverterFactory(GsonConverterFactory.create());
        } else {
            builder.addConverterFactory(StringConverterFactory.create());
        }
        if (time > NO_TIME_LIMIT) {
            client.connectTimeout(time, TimeUnit.SECONDS)
                    .writeTimeout(time, TimeUnit.SECONDS)
                    .readTimeout(time, TimeUnit.SECONDS);
        } else {
            client.connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS);
        }
        builder.client(client
                .build());
        return builder.build().create(cls);
    }
}
